#!/bin/bash

REPO_SERVER=192.168.20.160
TOOLS_DIR=/home/lavenliu/tools
APP_DIR=/application

# following steps for MySQL
useradd mysql -s /sbin/nologin -M

[ ! -d ${TOOLS_DIR} ] && mkdir -p ${TOOLS_DIR}

[ ! -d ${APP_DIR} ] && mkdir ${APP_DIR}

cd ${TOOLS_DIR}
wget http://${REPO_SERVER}/tools/mysql-5.5.32-linux2.6-x86_64.tar.gz

tar -xf mysql-5.5.32-linux2.6-x86_64.tar.gz
mv ${TOOLS_DIR}/mysql-5.5.32-linux2.6-x86_64 ${APP_DIR}/mysql-5.5.32
ln -s ${APP_DIR}/mysql-5.5.32 ${APP_DIR}/mysql

${APP_DIR}/mysql/scripts/mysql_install_db \
--basedir=/application/mysql \
--datadir=/application/mysql/data \
--user=mysql

# prepare the startup script
/bin/cp ${APP_DIR}/mysql/support-files/mysql.server /etc/init.d/mysqld
sed -i 's#/usr/local/mysql#/application/mysql#g' /etc/init.d/mysqld
chmod 755 /etc/init.d/mysqld

# prepare the my.cnf
/bin/cp ${APP_DIR}/mysql/support-files/my-medium.cnf /etc/my.cnf

# setup .so lib
cat >> /etc/ld.so.conf <<EOF
/application/mysql/lib/
EOF
/sbin/ldconfig

chown -R mysql.mysql ${APP_DIR}/mysql/

/etc/init.d/mysqld start
chkconfig mysqld on

# setup environment
echo "PATH=$PATH:/application/mysql/bin" >> ~/.bashrc
echo "export PATH" >> ~/.bashrc
. ~/.bashrc

# setup new mysql password
mysqladmin -uroot password "123456"

# delete extra database, such as test
mysql -uroot -p123456 -e "drop database test"

# delete extra users
mysql -uroot -p123456 -e "delete from mysql.user;"
mysql -uroot -p123456 -e "grant all on *.* to 'root'@'localhost' identified by '123456' with grant option;"
mysql -uroot -p123456 -e "flush privileges;"

